/**
 * 邮件发送模板新增编辑页
 */
import React from 'react';
import { Form, Card, Button, Input, Select, message, Checkbox, Spin, TreeSelect } from 'antd';
// import { Link } from 'umi';
import { get as getPath } from 'object-path';
import FileUpload from '@/components/Custom/FileUpload';
import { customUpload } from '@/utils/fileUpload';
import { useRequest, defaultFormatResult } from '@/hooks';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BraftEditor from 'braft-editor';
import pageTabUtil from '@/utils/pageTabUtil';
import { BottomAction } from '@/components';
import { PreviewModal } from './containers';
import { transformFileList } from '../utils';
import { getChannelColumns, addEmailTemplate, getEmailTemplate, updateEmailTemplate } from './service';
import styles from './index.less';

const { Option } = Select;

const templateTypeList = [
    { label: '发布/上线模板', value: 1 },
    { label: '更新模板', value: 2 },
    { label: '下线模板', value: 3 }
];

const EmailTemplateEdit = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const modalRef = React.useRef(null);

    // 获取渠道列表
    const { data: channelColumns, loading: columnsLoading } = useRequest(getChannelColumns, {
        initialData: [],
        formatResult: result => {
            const { code, data: resData, msg } = result;
            if (code === 10000) {
                return resData?.map(item => ({
                    title: item.columnName,
                    value: item.columnCode,
                    disabled: item.columnCode === 'positionName'
                }));
            }
            message.error(msg);
            return [];
        }
    });

    const defaultColumns = React.useMemo(() => {
        const filterOut = ['salaryRange'];
        return channelColumns?.filter(item => !filterOut.includes(item.value)).map(item => item.value) || undefined;
    }, [channelColumns]);

    const { data: info, loading, run: fetchDetail } = useRequest(getEmailTemplate, {
        manual: true,
        ...defaultFormatResult
    });

    React.useEffect(() => {
        if (query?.id) {
            fetchDetail(query?.id);
        }
    }, []);

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return pathname.includes('add');
    }, [location]);

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            // console.log('handleSubmit -> values', values);
            if (!err) {
                const { resourceRelation, openingRemarks, generalType, ...rest } = values;
                const params = {
                    ...rest,
                    generalType: generalType ? 1 : 0,
                    resourceRelation: resourceRelation?.uploadResourceFile
                        ? [resourceRelation?.uploadResourceFile]
                        : [],
                    openingRemarks: openingRemarks?.toHTML() || ''
                };
                // console.log(JSON.stringify(params));
                setSubmitLoading(true);
                if (isAddPage) {
                    addEmailTemplate(params)
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                message.success('操作成功');
                                pageTabUtil.goBack();
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                } else {
                    updateEmailTemplate({
                        ...rest,
                        ...params,
                        id: info?.id
                    })
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                message.success('操作成功');
                                pageTabUtil.goBack();
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                }
            }
        });
    };

    const handlePreview = e => {
        e.preventDefault();
        const { subject, openingRemarks, resourceRelation, recruitColumns = [] } = form.getFieldsValue();
        let str = openingRemarks?.toHTML() || '';
        str += '<br/>';
        const columns = channelColumns.filter(item => recruitColumns.includes(item.value));
        columns.forEach(item => {
            str += `<p style="text-indent:${6 - item?.title?.length}em;">${item.title}：</p>`;
        });
        modalRef.current.show({
            subject,
            openingRemarks: str,
            resourceRelation
        });
    };

    // 不允许添加尺寸大于10M的文件
    const myValidateFn = file => {
        if (file.size > 1024 * 1024 * 10) {
            message.error('图片不能大于10M！');
            return false;
        }
        return true;
    };

    // 报错提示
    const handleEditorChange = editorState => {
        const html = editorState.toHTML();
        // console.log(html);
        if (html.length > 20000) {
            message.error('邮件内容过多');
        }
    };

    const myUploadFn = param => {
        const onSuccess = (response, file) =>
            param.success({
                url: response.data[0].url,
                meta: {
                    id: file.name,
                    title: file.name,
                    alt: file.name
                }
            });
        customUpload({ files: param, onSuccess });
    };

    const controls = [
        'undo',
        'redo',
        'separator',
        'font-size',
        'line-height',
        'letter-spacing',
        'separator',
        'text-color',
        'bold',
        'italic',
        'underline',
        'strike-through',
        'separator',
        'superscript',
        'subscript',
        'remove-styles',
        'emoji',
        'separator',
        'text-indent',
        'text-align',
        'separator',
        'headings',
        'list-ul',
        'list-ol',
        'blockquote',
        'code',
        'separator',
        'media',
        'link',
        'hr',
        'separator',
        'clear'
    ];

    React.useEffect(() => {
        if (getPath(info, 'recruitChannelTemplateAttachmentFile')) {
            form.setFieldsValue({
                resourceRelation: transformFileList(getPath(info, 'recruitChannelTemplateAttachmentFile', []))
            });
        }
    }, [info]);

    const getColumns = arr => {
        if (arr && arr.length > 0) {
            return channelColumns.filter(item => arr.includes(item.value)).map(item => item.value);
        }
        return undefined;
    };

    return (
        <PageHeaderWrapper>
            <Card
                title={isAddPage ? '新增模板' : '编辑模板'}
                bordered={false}
                loading={loading}
                extra={
                    <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()} style={{ marginRight: 8 }}>
                            取消
                        </Button>
                        <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                            保存
                        </Button>
                    </BottomAction>
                }
            >
                <Form className={styles.formWrap} style={{ marginTop: 24 }}>
                    <Form.Item label="名称">
                        {getFieldDecorator('templateName', {
                            initialValue: getPath(info, 'templateName', ''),
                            rules: [
                                {
                                    required: true,
                                    message: '请输入名称'
                                }
                            ]
                        })(<Input placeholder="请输入名称" allowClear maxLength={20} />)}
                    </Form.Item>
                    <Form.Item label="邮件主题">
                        {getFieldDecorator('subject', {
                            initialValue: getPath(info, 'subject', ''),
                            rules: [
                                {
                                    required: true,
                                    message: '请输入邮件主题'
                                }
                            ]
                        })(<Input placeholder="请输入邮件主题" allowClear maxLength={100} />)}
                    </Form.Item>
                    <Form.Item label="模板类型">
                        {getFieldDecorator('templateType', {
                            rules: [
                                {
                                    required: true,
                                    message: '请选择模板类型'
                                }
                            ],
                            initialValue: getPath(info, 'templateType', undefined)
                        })(
                            <Select placeholder="请选择模板类型" getPopupContainer={trigger => trigger.parentNode}>
                                {templateTypeList?.map(item => (
                                    <Option value={item.value} key={item.value}>
                                        {item.label}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item label="是否通用">
                        {getFieldDecorator('generalType', {
                            valuePropName: 'checked',
                            initialValue: getPath(info, 'generalType', false)
                        })(<Checkbox>是</Checkbox>)}
                        <span style={{ color: 'rgba(0,0,0,0.5)' }}>
                            （同一个模板类型只可设置一次通用，以最后一次设置的为准）
                        </span>
                    </Form.Item>
                    <Form.Item label="模板附件">
                        {getFieldDecorator('resourceRelation')(
                            <FileUpload
                                checkFileSizeMsg="文件大小不能超过50MB！"
                                checkFileSize={50}
                                categoryCode="recruitChannelTemplateAttachmentFile"
                                checkFileType="TXT,DOC,DOCX,XLS,XLSX,PPT,PPTX,PDF,EDC,SSP,DWG,EDCS,
                                    BMP,JPG,PNG,TIF,GIF,PCX,TGA,EXIF,FPX,SVG,PSD,CDR,PCD,DXF,UFO,EPS,AI,
                                    RAW,WMF,WEBP,Xmind,ZIP,rar,zip,CAB,ARJ,LZH,TAR,GZ,ACE,UUE,BZ2,JAR,ISO,rp"
                                checkFileTypeMsg="附件格式不合规，请确认！"
                            >
                                <Button disabled={form.getFieldValue('resourceRelation')?.allFileList?.length > 4}>
                                    添加附件
                                </Button>
                            </FileUpload>
                        )}
                    </Form.Item>
                    <Form.Item label="邮件内容" required>
                        招聘需求字段+其他内容&nbsp;&nbsp;<a onClick={handlePreview}>效果预览</a>
                    </Form.Item>
                    <Form.Item label="招聘需求字段">
                        <Spin spinning={columnsLoading}>
                            {getFieldDecorator('recruitColumns', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择招聘需求字段'
                                    }
                                ],
                                initialValue:
                                    getPath(info, 'recruitColumns', [])?.length > 0
                                        ? getColumns(getPath(info, 'recruitColumns', []))
                                        : defaultColumns
                            })(
                                <TreeSelect
                                    multiple
                                    showSearch={false}
                                    treeData={channelColumns || []}
                                    treeCheckable
                                    showCheckedStrategy={TreeSelect.SHOW_PARENT}
                                    placeholder="请选择岗位信息发布字段"
                                    style={{
                                        width: '100%'
                                    }}
                                    dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                    getPopupContainer={trigger => trigger.parentNode}
                                />
                            )}
                        </Spin>
                    </Form.Item>
                    <Form.Item label="其他内容">
                        {getFieldDecorator('openingRemarks', {
                            initialValue: getPath(info, 'openingRemarks')
                                ? BraftEditor.createEditorState(`${getPath(info, 'openingRemarks')}`)
                                : BraftEditor.createEditorState(null),
                            validateTrigger: 'onBlur',
                            rules: [
                                {
                                    required: true,
                                    validator: (_, value, callback) => {
                                        if (value.isEmpty()) {
                                            callback('邮件内容不能为空');
                                        } else {
                                            callback();
                                        }
                                    },
                                    message: '邮件内容不能为空'
                                }
                            ]
                        })(
                            <BraftEditor
                                media={{
                                    uploadFn: myUploadFn,
                                    validateFn: myValidateFn,
                                    accepts: {
                                        image: 'image/png,image/jpeg,image/gif'
                                    }
                                }}
                                onChange={handleEditorChange}
                                placeholder="请输入邮件内容"
                                controls={controls}
                                excludeControls={['fullscreen']}
                                imageControls={[
                                    {
                                        onClick: block => {
                                            console.log(block);
                                        }
                                    },
                                    'align-left',
                                    'align-center',
                                    'align-right',
                                    'size',
                                    'remove'
                                ]}
                                contentStyle={{ height: 600 }}
                            />
                        )}
                    </Form.Item>
                </Form>
                <PreviewModal ref={modalRef} />
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(EmailTemplateEdit);
